package tfc_editor.GUI;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import tfc_editor.pastrytools.PastryManager;
import tfc_editor.userManagement.UserData;
import tfc_editor.userManagement.UserManagementException;
import tfc_editor.userManagement.UserUtils;

/**
 * Clase que gestiona la finestra per a crear usuaris.
 * @author Ismael Gonzalez Burgos
 */
public class FinestraCrearUsuari extends FinestraTFC implements ActionListener
{
	private static final long serialVersionUID = 1L;
	private PastryManager pm;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JPasswordField jPasswordField2;
    private javax.swing.JTextField jTextField1;

	/**
	 * Constructor.
	 * @param PM Punter a la clase PastryManager.
	 * @param parentEditor Punter a la clase pare del editor.
	 */
    public FinestraCrearUsuari(PastryManager PM,EditorGUI parentEditor)
    {
    	super(parentEditor);
    	super.Entrar();
    	pm = PM;
        initComponents();
        SetErrorLabel();
    }

	/**
	 * Funcio que compara els dos caps de passwords de la finestra.
	 * @return Si son iguals o no.
	 */
	public boolean ComparePasswords()
	{
		String p1 = new String(jPasswordField1.getPassword());
		String p2 = new String(jPasswordField2.getPassword());

		return p1.equals(p2);
	}

	/**
	 * Funcio per esbrinar si els camps amb els passwords son buits.
	 * @return Si algun dels caps es buit.
	 */
	public boolean PasswordsEmpty()
	{
		String p1 = new String(jPasswordField1.getPassword());
		String p2 = new String(jPasswordField2.getPassword());
		return (p1.equals("") || p2.equals(""));
	}

	/**
	 * Funcio que verifica que el camp de login sigui correcte.
	 * @return Si ho es o no.
	 */
	public boolean LoginLabelCorrect()
	{
		return jTextField1.getText().toString().length() > 0;	
	}

	/**
	 * Funcio per actualitzar l'estat del buto d'acceptar.
	 */
	public void UpdateCrearButton()
	{
		jButton1.setEnabled(ComparePasswords() && LoginLabelCorrect() && !PasswordsEmpty());
	}

	/**
	 * Funcio per actualitzar l'etiqueta d'error si n'hi ha.
	 */
	public void SetErrorLabel()
	{
		if (LoginLabelCorrect())
			if (ComparePasswords())
				if (PasswordsEmpty())
					jLabel4.setText("El password no pot estar buit");
				else
					jLabel4.setText("");
			else
	    		jLabel4.setText("El password és diferent");
		else 
   			jLabel4.setText("El login no pot ser buit");
    	
    	UpdateCrearButton();
	}

    /**
     * Funcio que inicia els components de la finestra.
     */
    public void initComponents()
    {
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();

        jButton1 = new javax.swing.JButton();
        jPasswordField1 = new javax.swing.JPasswordField();
        jPasswordField2 = new javax.swing.JPasswordField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setTitle("Crear usuari");

        jButton2.setText("Cancelar");
        jButton1.setText("Crear");
        jLabel2.setText("Paraula clau:");
        jLabel3.setText("Repetir paraula clau:");
        jLabel1.setText("Login desitjat:");
        
        jPasswordField1.addActionListener(this);
        jPasswordField2.addActionListener(this);
        jButton2.addActionListener(this);
        jButton1.addActionListener(this);
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter()
        {
            public void keyReleased(java.awt.event.KeyEvent evt)
            {
            	SetErrorLabel();
            }
            public void keyPressed(java.awt.event.KeyEvent evt)
            {
            	SetErrorLabel();
            }
            public void keyTyped(java.awt.event.KeyEvent evt)
            {
            	if (jTextField1.getText().length()>UserUtils.LOGIN_MAX_LEN)
            	{
            		jTextField1.setText(jTextField1.getText().substring(0,UserUtils.LOGIN_MAX_LEN));
            	}
            	SetErrorLabel();
            }
        });        

        jPasswordField2.addKeyListener(new java.awt.event.KeyAdapter()
        {
            public void keyReleased(java.awt.event.KeyEvent evt)
            {
            	SetErrorLabel();
            }
            public void keyPressed(java.awt.event.KeyEvent evt)
            {
            	SetErrorLabel();
            }
            public void keyTyped(java.awt.event.KeyEvent evt)
            {
            	SetErrorLabel();
            	String psw = new String(jPasswordField2.getPassword()); 
            	if (psw.length()>UserUtils.LOGIN_MAX_LEN)
            	{
            		jPasswordField2.setText(psw.substring(0,UserUtils.PASSWORD_MAX_LEN));
            	}
            }
        });

        jPasswordField1.addKeyListener(new java.awt.event.KeyAdapter()
        {
            public void keyReleased(java.awt.event.KeyEvent evt)
            {
            	SetErrorLabel();
            }
            public void keyPressed(java.awt.event.KeyEvent evt)
            {
            	SetErrorLabel();
            }
            public void keyTyped(java.awt.event.KeyEvent evt)
            {
            	SetErrorLabel();
            	String psw = new String(jPasswordField1.getPassword()); 
            	if (psw.length()>UserUtils.LOGIN_MAX_LEN)
            	{
            		jPasswordField1.setText(psw.substring(0,UserUtils.PASSWORD_MAX_LEN));
            	}
            }
        });
        
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jLabel4.setAutoscrolls(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel1))
                        .addGap(31, 31, 31)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2)))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        pack();
        InitC();
    }

    /**
     * Funcio que utilitzen les clases de test per a crear un usuari.
     * @param NewUser Login del nou usuari.
     * @param NewPassword Password del nou usuari.
     */
    public void TestSetUserToCreate(String NewUser,String NewPassword)
    {
    	jTextField1.setText(NewUser);
    	jPasswordField1.setText(NewPassword);
    	jPasswordField2.setText(NewPassword);
    	ActionButtonPressed();
    }

    /**
     * Funcio que s'executa quan es prem el buto d'accio.
     */
    public void ActionButtonPressed()
    {
		if (ComparePasswords())
		{
			try
			{
				CreateUserGUI(jTextField1.getText(),new String(jPasswordField1.getPassword()));
			} catch (Exception e)
			{
				System.out.println(e.getLocalizedMessage());
			}
		}
		super.Sortir();
    }

    /**
     * Funcio que es crida quan es produeix un event que afecta als nodes GUI registrats per a
     * escoltar events.
     * @param arg0 Event generat.
     */
	public void actionPerformed(ActionEvent arg0)
	{
		if (arg0.getSource()==jButton1)
    	{
			ActionButtonPressed();
    	}
		else if (arg0.getSource()==jButton2)
		{
			Sortir();
		}
	}

	/**
	 * Funcio que crea un usuari, pero aquesta funcio s'encarrega de la part Vista.
	 * @param login Cadena amb el nom de l'usuari a crear.
	 * @param password Cadena amb el password de l'usuari.
	 * @throws UserManagementException Excepcio indicant que no hem pogut crear l'usuari.
	 */
	public void CreateUserGUI(String login,String password) throws UserManagementException
    {
		UserData ud = new UserData(login,password);
		UserUtils uu = new UserUtils(pm);
		try
		{
			uu.WriteUser(ud);
		}
		catch (UserManagementException e)
		{
        	JOptionPane.showMessageDialog(this, "No es pot crear l'usuari perque ja existeix",
        			"Error en crear l'usuari",JOptionPane.ERROR_MESSAGE);
		}
    }
}
